package com.lyons.easyweb.modular.redis;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.lyons.easyweb.common.RedisService;
import com.lyons.easyweb.core.util.LayuiPageInfo;

@Controller
@RequestMapping("/sys/redis")
public class RedisController {

	@Autowired
	private RedisService redis;

	@ResponseBody
	@RequestMapping("/list")
	public LayuiPageInfo list(@RequestParam(value = "key", required = false) String key) {

		Set<String> set;

		if (ObjectUtils.isEmpty(key)) {
			set = redis.getkeyAll();
		} else {
			set = redis.keys(key);
		}

		List<RedisRespVo> list = Lists.newArrayList();
		if (null != set && set.size() > 0) {
			set.forEach(e -> {

				RedisRespVo respVo = new RedisRespVo();
				respVo.setKey(e);

				list.add(respVo);
			});
		}
		return LayuiPageInfo.ok(0L, list);
	}

	@ResponseBody
	@RequestMapping("/delete")
	public LayuiPageInfo delete(String key) {

		redis.delete(key);
		return LayuiPageInfo.ok();
	}

	@RequestMapping("/clearRedisAll")
	public void clearRedisAll(HttpServletResponse response) throws IOException {

		redis.clearAll();
		response.sendRedirect("/page/login.html");
	}

	@RequestMapping("/deleteAll")
	public LayuiPageInfo deleteAll() {

		redis.clearAll();
		return LayuiPageInfo.ok();
	}
}

class RedisRespVo {

	private String key;
	private Object value;

	public RedisRespVo() {

	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public Object getValue() {
		return value;
	}

	public void setValue(Object value) {
		this.value = value;
	}

}